#!/usr/bin/python3
import sys
from operator import itemgetter

try:
    t = int(input())
    if t < 1 or t > 100:
        sys.exit(0)
    for i in range(t):
        n,m = list(map(int, input().split()))
        count = 0
        d = {}
        nd = {}
        for j in range(n):
            for s in input():
                if s in d.keys():
                    d[s]=d[s]+1
                else:
                    d[s]=1
        for key, val in d.items():
            l = []
            if str(val) in nd.keys():
                l = nd[str(val)]+ list(key)
                nd[str(val)] = l
            else:
                l.append(key)
                nd[str(val)] = l

        sort_d= sorted(nd.items(), key=lambda k: int(k[0]),reverse=True)
        print(len(d.keys()))
        for y in sort_d:
            y[1].sort()
            for s in y[1]:
                print("%s %s" % (y[0],s))


except ValueError:
    pass
except EOFError:
    pass
except MemoryError:
    pass
